package com.aduerr.v1shouyin.mvp.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bertsir.zbar.CameraPreview;
import cn.bertsir.zbar.Qr.Symbol;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.ScanCallback;
import cn.bertsir.zbar.view.ScanView;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.*;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.*;
import com.aduerr.v1shouyin.view.BandOrUnbandGuidResultDialog;
import com.orhanobut.hawk.Hawk;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.*;

import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.aduerr.v1shouyin.common.Constants.MEMBER_SCANCODECOLLECTION_QR;

/**
 * 作者: Nathans'Liu
 * 邮箱: a1053128464@qq.com
 * 时间: 2018/10/26 13:37
 * 描述:
 */
public class ScanningActivity extends Activity {
    public Unbinder unbinder;

    @BindView(R.id.tv_describe)
    TextView tv_describe;
    @BindView(R.id.tv_realmoney_capture)
    TextView tv_realmoney_capture;
    @BindView(R.id.btn_shurulajuanma)
    Button btn_shurukajuanma;
    @BindView(R.id.shurulajuanma)
    RelativeLayout shurulajuanma;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_right)
    TextView tvChangeCamera;
    @BindView(R.id.tv_rmb_01)
    TextView tvRMB01;
    @BindView(R.id.iv_camera)
    ImageView ivCamera;
    @BindView(R.id.ll_camera)
    LinearLayout llCamera;

    private String sendmoney, memberNo, beizhu, fromOrderID, realMoney;
    private int captureType;
    private CameraPreview cp;
    //    private SoundPool soundPool;
    private ScanView sv;
    //    private BeepManager beepManager;
    private SweetAlertDialog pDialog;
    private Date startDate;
    private Date endDate;
    private long looptime = 1 * 30 * 1000;
    private BandOrUnbandGuidResultDialog bandGuidfaid;
    private BandOrUnbandGuidResultDialog bandOrUnbandGuidResultDialog;
    private boolean isMember;
    /**
     * 扫描成功回调
     */
    private ScanCallback resultCallback = new ScanCallback() {
        @Override
        public void onScanResult(String result) {
            //扫描完成是否播放bi~的声音
           /* if (true) {
                soundPool.play(1, 1, 1, 0, 0, 1);
            }*/
            /*if (cp != null) {
                cp.setFlash(false);
            }*/
            handleDecode(result);
        }
    };

    public static boolean isActivityRunning(Context mContext, String activityClassName) {
        ActivityManager activityManager =
                (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> info = activityManager.getRunningTasks(1);
        if(info != null && info.size() > 0) {
            ComponentName component = info.get(0).topActivity;
            if(activityClassName.equals(component.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      /*  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }*/
        Symbol.scanType = 3;
        Symbol.scanFormat = 13;
        Symbol.is_only_scan_center = false;
        setContentView(R.layout.activity_scanning);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(cp != null) {
            cp.setScanCallback(resultCallback);
            cp.start();
        }
        sv.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(cp != null) {
            cp.stop();
        }
        sv.onPause();
//        beepManager.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(cp != null) {
            cp.setFlash(false);
            cp.stop();
        }
        if(pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
        unbinder.unbind();
//        soundPool.release();
        looptime = 0;
        endDate = startDate;
    }

    private void initView() {

        Intent intent = getIntent();
        sendmoney = intent.getStringExtra("sendmoney");
        memberNo = intent.getStringExtra("scanMemberNo");
        isMember = intent.getBooleanExtra("isMember", false);
        //备注
        beizhu = intent.getStringExtra("beizhu");
        //        LogUtils.e("备注:", "接受计算器界面的备注信息" + beizhu);
        fromOrderID = intent.getStringExtra(Constants.FROMORDERID);
        realMoney = intent.getStringExtra(Constants.REALMONEY);
        captureType = intent.getIntExtra(Constants.QRCODE_CAPUTER,
                Constants.SCANCODECOLLECTION_QR);

        switch(captureType) {
            case Constants.MEMBER_RECHARGE_QR:
                tv_title.setText(getResources().getString(R.string.huiyuanchognzhi));
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.GONE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("将会员码放入框内，将自动扫描");
                break;
            case Constants.MEMBER_SCANCODEJIFEN_QR:
                tv_title.setText("会员积分");
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.GONE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("将会员码放入框内，将自动扫描");
                break;
            case Constants.CARD_COUPONS_VERIFY_QR:
                tv_title.setText(getResources().getString(R.string.kaquanhexiao));
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.GONE);
                llCamera.setVisibility(View.VISIBLE);
                ivCamera.setVisibility(View.GONE);
                tvChangeCamera.setText("核销记录");
                tv_describe.setText("请扫描顾客的卡券码");
         /*       hexiaojilu.setVisibility(View.VISIBLE);
                hexiaojilu.setText("核销记录");
                hexiaojilu.setTextColor(getResources().getColor(R.color.white));*/
                //底部输入
                shurulajuanma.setVisibility(View.VISIBLE);
                btn_shurukajuanma.setText("输入卡券码");

                break;
            case Constants.REFUND_QR:
                tv_title.setText(getResources().getString(R.string.tuikuan));
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.GONE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("将二维码/条形码放入框内自动扫描");
               /* hexiaojilu.setVisibility(View.VISIBLE);
                hexiaojilu.setText("退款记录");
                hexiaojilu.setTextColor(getResources().getColor(R.color.white));*/

                shurulajuanma.setVisibility(View.VISIBLE);
                btn_shurukajuanma.setText("输入订单号");
                break;
            case Constants.SCANCODECOLLECTION_QR:
                //showRealMoneyText
                String cardshaoma = getIntent().getStringExtra("cardshaoma");
                if(TextUtils.isEmpty(cardshaoma)) {
                    tv_title.setText(getResources().getString(R.string.text_saoma_pay));
                    tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                    tv_realmoney_capture.setText(realMoney);
                    tvRMB01.setVisibility(View.VISIBLE);
                    llCamera.setVisibility(View.GONE);
                    tv_describe.setText("将二维码/条形码放入框内自动扫描");

                } else {//不为空的话,就是卡券核销时,为1时就是去扫码(微信和支付宝)
                    if(TextUtils.equals(cardshaoma, "1")) {
                        tv_title.setText("微信/支付宝扫码");
                        tv_title.setTextColor(ContextCompat.getColor(this,
                                R.color.white));
                        tv_realmoney_capture.setText(realMoney);
                        tvRMB01.setVisibility(View.VISIBLE);
                        llCamera.setVisibility(View.VISIBLE);
                        tv_describe.setText("将微信/支付宝收款码放入框内自动扫描");
                    }
                }

//                tv_title.setText(getResources().getString(R.string.text_saoma_pay));
//                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
//                tv_realmoney_capture.setText(realMoney + "元");
                break;
            case MEMBER_SCANCODECOLLECTION_QR:
                //showRealMoneyText
                tv_title.setText(getResources().getString(R.string.text_saoma_pay));
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText(realMoney);
                tvRMB01.setVisibility(View.VISIBLE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("将二维码/条形码放入框内自动扫描");
                break;
            case Constants.MEMBER_PAYMENT_QR:
                tv_title.setText(getResources().getString(R.string.text_huiyuan_pay));
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.INVISIBLE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("将会员码放入框内，将自动扫描");
                break;
            case Constants.PUBLIC_PRAISE_DETAILS:
                tv_title.setText("口碑核销");
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.INVISIBLE);
                llCamera.setVisibility(View.VISIBLE);
                ivCamera.setVisibility(View.GONE);
                tvChangeCamera.setText("核销记录");
                tv_describe.setText("请扫描顾客的卡券码");
      /*          hexiaojilu.setVisibility(View.VISIBLE);
                hexiaojilu.setText("核销记录");
                hexiaojilu.setTextColor(getResources().getColor(R.color.white));*/
                //底部输入
                shurulajuanma.setVisibility(View.VISIBLE);
                btn_shurukajuanma.setText("输入卡券码");
                break;
            case Constants.BIND_GUID_QR:
                tv_title.setText("绑定GUID");
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.INVISIBLE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("请扫描GUID二维码");
                shurulajuanma.setVisibility(View.VISIBLE);
                btn_shurukajuanma.setText("输入GUID");
                break;
            case Constants.PRE_AUTHO_MONEY: //扫码预授权
                tv_describe.setText("请对准顾客的付款码");
                tv_title.setText("收款");
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.INVISIBLE);
//                mTvTitle.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText(realMoney);
                break;
            case Constants.PRE_AUTHO_REFUND: //预授权退押 撤销
                tv_title.setText("预授权完成/撤销");
                tv_describe.setText("请扫描订单条形码");
                tv_realmoney_capture.setText("");
                tvRMB01.setVisibility(View.INVISIBLE);
//                mTvTitle.setTextColor(ContextCompat.getColor(this, R.color.white));
                shurulajuanma.setVisibility(View.VISIBLE);
                btn_shurukajuanma.setText("输入预授权订单号");
                break;
            case Constants.MEMBER_CONSUME_NEW:
                tv_title.setText(getResources().getString(R.string.text_saoma_pay));
                tv_title.setTextColor(ContextCompat.getColor(this, R.color.white));
                tv_realmoney_capture.setText(realMoney);
                tvRMB01.setVisibility(View.VISIBLE);
                llCamera.setVisibility(View.GONE);
                tv_describe.setText("将二维码/条形码放入框内自动扫描");
                break;


        }

        cp = (CameraPreview) findViewById(cn.bertsir.zbar.R.id.cp);
        //bi~
//        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        sv = (ScanView) findViewById(cn.bertsir.zbar.R.id.sv);
        sv.setType(1);
        sv.startScan();
        sv.setCornerColor(Color.parseColor("#005fee"));//设置扫描框颜色
        sv.setLineSpeed(QrConfig.LINE_MEDIUM);//设置扫描线速度
        sv.setLineColor(Color.parseColor("#005fee"));//设置扫描线颜色
        //设备震动
//        beepManager = new BeepManager(this);
        initEvent();
    }

    private void initEvent() {
        btn_shurukajuanma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(captureType == Constants.BIND_GUID_QR) {
                    finish();
                } else {
                    Intent intent = new Intent(ScanningActivity.this,
                            HandInputActivity.class);
                    intent.putExtra(Constants.QRCODE_CAPUTER, captureType);
                    if(captureType == Constants.CARD_COUPONS_VERIFY_QR || captureType == Constants.PUBLIC_PRAISE_DETAILS) {
                        intent.putExtra("tag", getIntent().getStringExtra("tag"));
                    }
                    startActivity(intent);
                }
            }
        });

        llCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(captureType == Constants.CARD_COUPONS_VERIFY_QR) {
                    Intent intentHexiao = new Intent(ScanningActivity.this,
                            HexiaoJiluActivity.class);
                    intentHexiao.putExtra("tag", "xianxia");
                    startActivity(intentHexiao);
                } else if(captureType == Constants.PUBLIC_PRAISE_DETAILS) {
                    startActivity(new Intent(ScanningActivity.this,
                            KouBeiHeXiaoRecordActivity.class));
                }
            }
        });

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    //拿到扫描的卡券的详情信息
    private void toKaQuanDetail(String erWeiMaResult) {

        if(getIntent().getStringExtra("tag").equals("xianxia")) {
            if(erWeiMaResult.startsWith("21") || erWeiMaResult.startsWith("34") || erWeiMaResult.startsWith("8") || erWeiMaResult.startsWith("25")) {
                //JIUDIAN，MENPIAO KAITOUHUIYUAN
                HashMap<String, String> addParams = new HashMap<>();
                addParams.put("code", erWeiMaResult);//86008032893055438199  test
                APIRetrofit.getAPIService().getOtherCardDetail(RXRequest.getXingPosParams(addParams, this))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(otherCardEntity -> {
                            int success = otherCardEntity.getSuccess();
                            if(success == 1) {
                                //跳转到卡券信息的详情界面
                                if(otherCardEntity != null) {
                                    Intent intent = new Intent(ScanningActivity.this,
                                            KaQuanDetailNewActivity.class);
                                    if(erWeiMaResult.startsWith("21")) {
                                        intent.putExtra("type", CardType.JIUDIAN.name());
                                    } else if(erWeiMaResult.startsWith("34")) {
                                        intent.putExtra("type",
                                                CardType.MENPIAOANDTUANGOU.name());
                                    } else if(erWeiMaResult.startsWith("25")) {
                                        intent.putExtra("type",
                                                CardType.MENPIAOANDTUANGOU.name());
                                    } else {
                                        intent.putExtra("type", CardType.LIPIN.name());
                                    }
                                    intent.putExtra("tag", "xianxia");
                                    intent.putExtra("Data", otherCardEntity);
                                    intent.putExtra("erWeiMaResult", erWeiMaResult);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    String erMsg = otherCardEntity.getErrMsg();
                                    ToastUtils.showToast(ScanningActivity.this, erMsg);
                                }

                            } else if(success == -4) {
                                //没有成功
                                String erMsg = otherCardEntity.getErrMsg();
                                ToastUtils.showToast(ScanningActivity.this, erMsg + "");
                            }
//                            KaQuanXiangQingEntity.DataBean KaQuanData =
//                            kaquanhexiaoEntity.getData();
//                            Intent intent = new Intent(ScanningActivity.this,
//                            KaQuanDetailActivity.class);
//                            intent.putExtra("isuse", true);
//                            intent.putExtra("Data", KaQuanData);
//                            startActivity(intent);
//                        } else {
//                            String erMsg = kaquanhexiaoEntity.getErrMsg();
//                            ToastUtils.showToast(ScanningActivity.this, erMsg + "");
//                        }


                        }, throwable -> {

                        });


            } else {
                //WX
                HashMap<String, String> addParams = new HashMap<>();
                addParams.put("scanTicketNo", erWeiMaResult);//86008032893055438199  test
                APIRetrofit.getAPIService().getKaQuanXiangQingDetail(RXRequest.getXingPosParams(addParams, this))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(kaQuanXiangQingEntity -> {
                            int success = kaQuanXiangQingEntity.getSuccess();
                            if(success == 1) {
                                //跳转到卡券信息的详情界面
                                List<KaQuanXiangQingEntity.DataBean> data =
                                        kaQuanXiangQingEntity.getData();
                                //有数据,
                                if(data.size() > 0) {
                                    KaQuanXiangQingEntity.DataBean dataBean = data.get(0);
                                    List<KaQuanXiangQingEntity.DataBean.ListBean> list
                                            = dataBean.getList();
                                    KaQuanXiangQingEntity.DataBean.ListBean listBean =
                                            list.get(0);
//                                    if (listBean.getIsuse()==1){
//                                        ToastUtils.showToast(this,"该券已经被核销");
//
//                                    }else {
                                    Intent intent = new Intent(ScanningActivity.this,
                                            KaQuanDetailNewActivity.class);
                                    int type = Integer.parseInt(listBean.getType());
                                    intent.putExtra("type", CardType.WX.name());
                                    intent.putExtra("tag", "xianxia");
                                    intent.putExtra("Data", listBean);
                                    intent.putExtra("erWeiMaResult", erWeiMaResult);
                                    startActivity(intent);
                                    finish();
//                                    }
                                } else {
                                    String erMsg = kaQuanXiangQingEntity.getErrMsg();
                                    ToastUtils.showToast(ScanningActivity.this,
                                            erMsg + "");
                                }

                            } else if(success == -4) {
                                //没有成功
                                String erMsg = kaQuanXiangQingEntity.getErrMsg();
                                ToastUtils.showToast(ScanningActivity.this, erMsg + "");
                            }


                        }, throwable -> {

                        });
            }
        } else {
            //口碑核销
            HashMap<String, String> addParams = new HashMap<>();
            addParams.put("TicketID", erWeiMaResult);//86008032893055438199  test
            APIRetrofit.getAPIService().getKouBeiquanDetail(RXRequest.getXingPosParams(addParams, this))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(kouBeiTicktEntity -> {
                        int success = kouBeiTicktEntity.getSuccess();
                        if(success == 1) {
                            //跳转到卡券信息的详情界面
                            KouBeiTicktEntity.DataBean data = kouBeiTicktEntity.getData();
                            //有数据,
                            if(data != null) {
                                Intent intent = new Intent(ScanningActivity.this,
                                        KaQuanDetailNewActivity.class);
                                intent.putExtra("type", CardType.KOUBEI.name());
                                intent.putExtra("tag", "koubei");
                                intent.putExtra("Data", data);
                                intent.putExtra("erWeiMaResult", erWeiMaResult);
                                startActivity(intent);
                                finish();
                            } else {
                                ToastUtils.showToast(ScanningActivity.this, "没有该卡券码");
                            }

                        } else if(success == -4) {
                            //没有成功
                            String erMsg = kouBeiTicktEntity.getErrMsg();
                            ToastUtils.showToast(ScanningActivity.this, erMsg + "");
                        } else {
                            ToastUtils.showToast(ScanningActivity.this,
                                    kouBeiTicktEntity.getErrMsg() + "");
                        }

                    }, throwable -> {

                    });
        }

    }

    private void toTuikuanDetail(String erWeiMaResult) {
        if(TextUtils.isEmpty(erWeiMaResult)) {
            ToastUtils.showToast(ScanningActivity.this, "输入不能为空");
            return;
        }
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", erWeiMaResult);//86008032893055438199  test
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<OrderGetPosOrderLEntity>() {
                    @Override
                    public void onNext(OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
                        //                    if (Tools.isAvailable
                        //                    (orderGetPosOrderLEntity)) return;
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            List<OrderGetPosOrderLEntity.DataBean> data =
                                    orderGetPosOrderLEntity.getData();
                            //会员消费的订单数必须大于0
                            if(data.size() == 0) {
                                ToastUtils.showToast(ScanningActivity.this, "订单不存在!");
                                return;
                            }

                            OrderGetPosOrderLEntity.DataBean.ListBean listBean =
                                    data.get(0).getList().get(0);
//                            OrderdetailEntity.OrderinfoBean orderinfo =
//                            orderdetailentity.getOrderinfo();

                            if(listBean != null) {
                                Intent intent = new Intent(ScanningActivity.this,
                                        RefoundMoneyDetailActivity.class);
                                intent.putExtra("date", listBean);
//                                intent.putExtra("ordernumber", editContent);
                                startActivity(intent);
                                finish();
                            } else {
                                ToastUtils.showToast(ScanningActivity.this, "订单信息为空");
                            }

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(ScanningActivity.this,
                                    ScanningActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(orderGetPosOrderLEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            errorClos();
                        } else {
                            ToastUtils.showToast(ScanningActivity.this,
                                    orderGetPosOrderLEntity.getErrMsg() + "");

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void errorClos() {
        //        SharedPreferencesUtils.remove(ScanningActivity.this, "autologin");
        //        SharedPreferencesUtils.remove(ScanningActivity.this, "remberpassword");
        //        startActivity(new Intent(ScanningActivity.this, LoginActivity.class));
        ScanningActivity.this.finish();
    }

    /**
     * A valid barcode has been found, so give an indication of success and show
     * the results.
     */
    public void handleDecode(String scanning) {
        //设备震动
//        beepManager.playBeepSoundAndVibrate();

        if(TextUtils.isEmpty(scanning)) {
            ToastUtils.showToast(ScanningActivity.this,
                    getResources().getString(R.string.text_member_recharge_saomashibai));
        } else {
            switch(captureType) {
                case Constants.MEMBER_RECHARGE_QR:
                    toScanMemberInfor(scanning);
                    break;
                case Constants.MEMBER_SCANCODEJIFEN_QR:
                    toScanMemberInfor(scanning);
                    break;
                case Constants.CARD_COUPONS_VERIFY_QR:
                    //跳转到卡券详情的界面   拿到的是卡券的编号码
                    toKaQuanDetail(scanning);
                    break;
                case Constants.REFUND_QR:
                    toTuikuanDetail(scanning);
                    break;
                case Constants.SCANCODECOLLECTION_QR://扫码收款
                    toScanPayMoney(scanning);
                    break;
                case Constants.MEMBER_PAYMENT_QR://会员消费
                    getMemberConfig(scanning);
                    break;
                case MEMBER_SCANCODECOLLECTION_QR://会员扫码充值
                    String orderId  = getIntent().getStringExtra("orderid");
                    toMemberScanPayMoney(scanning);
                    break;
                case Constants.PUBLIC_PRAISE_DETAILS://口碑核销
                    toKaQuanDetail(scanning);
                    break;
                case Constants.BIND_GUID_QR:
                    new Thread() {
                        public void run() {
                            postNetForBandGuid(scanning);
                        }
                    }.start();
                    break;
                case Constants.PRE_AUTHO_MONEY: //扫码预授权
                    preAuthoMoney(scanning);
                    break;
                case Constants.PRE_AUTHO_REFUND: //预授权撤销、退押
                    Intent intentPre = new Intent(ScanningActivity.this,
                            PreAuthoOrderActivity.class);
                    intentPre.putExtra("orderid", scanning);
                    intentPre.putExtra("tag", "detail");
                    startActivity(intentPre);
                    finish();
                    break;
                case Constants.MEMBER_CONSUME_NEW: //会员扫码支付
                    memberScanConsume(scanning);
                    break;
            }
        }
    }

    private void getMemberConfig(String scanning) {
        HashMap<String, String> addParams = new HashMap<>();
        APIRetrofit.getAPIService().getMemberConfig(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity -> {
                    if(entity.getSuccess() == 1) {
                        boolean open = entity.getData().isIsAggregatePay();
                        if(open) { //开通分离支付
                            toScanMemberInfor(scanning);
                        } else { //未开通
                            toHuiyuanMoney(scanning, realMoney);
                        }
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    ToastUtils.showToast(this, "网络异常");
                });
    }

    //会员充值  扫码
    private void toMemberScanPayMoney(String erWeiMaResult) {
        if(TextUtils.isEmpty(realMoney)) return;
        if(TextUtils.isEmpty(fromOrderID)) return;
        if(!isNumeric(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("FromOrderID", fromOrderID);
        addParams.put("payMoney", realMoney);
        addParams.put("PayType", "2");
        addParams.put("bz", beizhu + "");
        addParams.put("scanPayNo", erWeiMaResult);
        APIRetrofit.getAPIService().SaoMaPay(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<SaoMaEntity>() {
                    @Override
                    public void onNext(SaoMaEntity saoMaEntity) {
                        if(saoMaEntity.getSuccess() == 1) {
                            String orderid = saoMaEntity.getOrderid();
                            startDate = new Date(System.currentTimeMillis());
                            payState(orderid, 5418, realMoney, beizhu);//5418会员扫码充值
                            // 5419扫码收款
                        } else {
                            ToastUtils.showToast(ScanningActivity.this,
                                    saoMaEntity.getErrMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });

    }

    private void toHuiyuanMoney(String erWeiMaResult, String realMoney) {
        if(TextUtils.isEmpty(realMoney)) return;
        if(!isNumeric(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanmemberno", erWeiMaResult);
        addParams.put("paymoney", "-" + realMoney);
        APIRetrofit.getAPIService().MemberToPay(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MemberToPayEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(ScanningActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("正在付款中");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull MemberToPayEntity memberToPayEntity) {
//                        if (Tools.isAvailable(memberToPayEntity)) return;
                        int success = memberToPayEntity.getSuccess();
                        if(success == 1) {
                            Intent intent = new Intent(ScanningActivity.this,
                                    ResultActivity.class);
                            intent.putExtra("money",
                                    memberToPayEntity.getData().getChangemoney().replace("-", ""));
                            intent.putExtra("beizhu", beizhu);
                            intent.putExtra("sucess", "6");
                            intent.putExtra("scanMemberNo", erWeiMaResult);
                            intent.putExtra("orderid", memberToPayEntity.getData().getOrderid());
                            if(memberToPayEntity != null) {
                                intent.putExtra("memberInfo",
                                        memberToPayEntity.getData());
                            }
                            intent.putExtra("datebeen", memberToPayEntity);
                            // TODO: 2018/1/19 0019 再次请求会员详情的数据然后一并传入到resultactivity中
//                            toScanMemberInfor(erWeiMaResult, realMoney, beizhu, "6",
//                            memberToPayEntity);
                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(ScanningActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(ScanningActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(ScanningActivity.this,
                                    ScanningActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberToPayEntity.getErrMsg());
                            SharedPreferencesUtils.remove(ScanningActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(ScanningActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(ScanningActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {

                            pDialog.setTitleText(memberToPayEntity.getErrMsg())
                                    .setConfirmText("重新收款")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            pDialog.dismissWithAnimation();
                                            finish();
                                        }
                                    })
                                    .changeAlertType(SweetAlertDialog.ERROR_TYPE);


                            /*ToastUtils.showToast(ScanningActivity.this, "" +
                            memberToPayEntity.getErrMsg());
                            Intent intent = new Intent(ScanningActivity.this,
                            ResultActivity.class);
                            intent.putExtra("money", realMoney);
                            intent.putExtra("sucess", "0");
                            startActivity(intent);
                            finish();*/
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this,
                                    e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                        }
                        Intent intent = new Intent(ScanningActivity.this,
                                ResultActivity.class);
                        intent.putExtra("money", realMoney);
                        intent.putExtra("sucess", "0");
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    //计算器首页的会员支付(余额充足&余额不足的情况)
    private void toHuiyuanMoney(String erWeiMaResult) {
        if(TextUtils.isEmpty(realMoney)) return;
        if(!isNumeric(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanMemberNo", erWeiMaResult);
//        addParams.put("payMoney", "-" + realMoney);
        APIRetrofit.getAPIService().getMemberinfo(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<MemberInfoEntity>() {
                    @Override
                    public void onNext(MemberInfoEntity memberInfoEntity) {
                        //                    if (Tools.isAvailable(memberInfoEntity))
                        //                    return;
                        //// TODO: 2017/12/11 0011  去判断金额是否够用
                        int success = memberInfoEntity.getSuccess();
                        if(success == 1) {
                            String balance = memberInfoEntity.getData().getBalance();
                            Double abalance = Double.valueOf(balance);
                            Double arealMoney = Double.valueOf(realMoney);
                            if(abalance < arealMoney) {
                                ToastUtils.showToast(ScanningActivity.this, "余额不足");
                                // TODO: 2017/12/11 0011  跳转到充值界面
                                Intent intent = new Intent(ScanningActivity.this,
                                        MemberInfoActivity.class);
                                intent.putExtra("realMoney", realMoney);
                                intent.putExtra("showtype", "0");
                                intent.putExtra("beizhu", beizhu);
                                intent.putExtra("scanMemberNo", erWeiMaResult);
                                intent.putExtra("memberinfo", memberInfoEntity);
                                startActivity(intent);
                                finish();

                            } else {
                                // TODO: 2017/12/11 0011 跳转到消费界面   就是会员详情页面
                                Intent intent = new Intent(ScanningActivity.this,
                                        MemberInfoActivity.class);
                                intent.putExtra("realMoney", realMoney);
                                intent.putExtra("showtype", "1");
                                intent.putExtra("beizhu", beizhu);
                                intent.putExtra("scanMemberNo", erWeiMaResult);
                                intent.putExtra("memberinfo", memberInfoEntity);
                                startActivity(intent);
                                finish();
                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(ScanningActivity.this,
                                    ScanningActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberInfoEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            errorClos();
                        } else {
                            ToastUtils.showToast(ScanningActivity.this,
                                    "" + memberInfoEntity.getErrMsg());
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    private void toScanMemberInfor(String erWeiMaResult) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanMemberNo", erWeiMaResult);
        APIRetrofit.getAPIService().getMemberinfo(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<MemberInfoEntity>() {
                    @Override
                    public void onNext(MemberInfoEntity memberInfoEntity) {
                        int success = memberInfoEntity.getSuccess();
                        if(success == 1) {
//                            startActivity(getFragmentIntent(Constants
//                            .MEMBERRECHARGE_FRAGMENT));
                            Intent intent = null;
                            if(captureType == Constants.MEMBER_RECHARGE_QR) {
                                intent = new Intent(ScanningActivity.this,
                                        MemberInchargActivity.class);
                            } else if(captureType == Constants.MEMBER_SCANCODEJIFEN_QR) {
                                intent = new Intent(ScanningActivity.this,
                                        VIPIntegralActivity.class);
                            } else if(captureType == Constants.MEMBER_PAYMENT_QR) {
                                intent = new Intent(ScanningActivity.this,
                                        NewMemberToPayActivity.class);
                            }
                            intent.putExtra("realMoney", realMoney);
//                            intent.putExtra("showtype", "0");
                            intent.putExtra("beizhu", beizhu);
                            intent.putExtra("scanMemberNo", erWeiMaResult);
                            intent.putExtra("memberinfo", memberInfoEntity);

                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(ScanningActivity.this,
                                    ScanningActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberInfoEntity.getErrMsg());
                            //// TODO: 2017/12/9 0009 去登录的界面
                            //扫码错误，弹出提示且关闭
                            errorClos();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 扫描二维码获取订单号
     *
     * @param erWeiMaResult
     */
    private void toScanPayMoney(String erWeiMaResult) {
        if(TextUtils.isEmpty(realMoney)) return;
        if(!isNumeric(erWeiMaResult)) return;
        LogUtils.e("erWeiMaResult", "" + erWeiMaResult);

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("paymoney", realMoney);
//        addParams.put("PayType", "2");
        addParams.put("bz", beizhu + "");
        addParams.put("scanpayno", erWeiMaResult);
        APIRetrofit.getAPIService().SaoMaPay(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SaoMaEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(ScanningActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("正在付款中");
                            pDialog.setCancelable(false);
                            pDialog.show();
                        }
                    }

                    @Override
                    public void onNext(@NonNull SaoMaEntity saoMaEntity) {

                        int success = saoMaEntity.getSuccess();
                        if(success == 1) {
                            String orderid = saoMaEntity.getOrderid();
                            startDate = new Date(System.currentTimeMillis());
                            payState(orderid, 5419, realMoney, beizhu);
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(ScanningActivity.this,
                                    ScanningActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(saoMaEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            errorClos();
                        } else {
                            ToastUtils.showToast(ScanningActivity.this,
                                    saoMaEntity.getErrMsg());
                            if(pDialog != null) {
                                pDialog.dismiss();
                                pDialog = null;
                                errorClos();
                            }
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                        if(pDialog != null) {
                            pDialog.dismiss();
                            errorClos();
                            pDialog = null;
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 获取支付状态
     *
     * @param //5418会员扫码充值 5419扫码收款
     */
    private void payState(String orderid, int resulttype, String money, String beizhu) {
        if(TextUtils.isEmpty(orderid)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", orderid);
        APIRetrofit.getAPIService().payState(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PayStateEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if(pDialog == null) {
                            pDialog = new SweetAlertDialog(ScanningActivity.this,
                                    SweetAlertDialog.PROGRESS_TYPE);
                            pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                    "#005fee"));
                            pDialog.setTitleText("正在付款中");
                            pDialog.setCancelable(true);
                            pDialog.show();
                        }

                    }

                    @Override
                    public void onNext(@NonNull PayStateEntity payStateEntity) {
//                        if (Tools.isAvailable(payStateEntity)) return;
                        int success = payStateEntity.getSuccess();
                        if(success == 1) {

                            MemberInfoEntity.DataBean memberinfo =
                                    (MemberInfoEntity.DataBean) getIntent().getSerializableExtra("beformemberincahrgeinfo");
                            //付款成功

                            if(resulttype == 5418) {//5418会员扫码充值   5419扫码收款
//                                intent.putExtra("sucess", "3");
//                                //会员的条形码的号码
//                                intent.putExtra("scanMemberNo", memberNo);
//                                intent.putExtra("sendmoney", sendmoney);
//                                LogUtils.e("scanMemberNo", "zxing页面scanMemberNo=" +
//                                memberNo+"zxing页面sendmoney"+sendmoney);

                                // TODO: 2018/1/19 0019   请求服务器拿到会员的信息
                                postnetformemberinfo(memberNo, payStateEntity,
                                        memberinfo, orderid, money, "3", sendmoney,
                                        beizhu);


                            } else {//扫码成功 5419
                                Intent intent = new Intent(ScanningActivity.this,
                                        ResultActivity.class);
//                            Bundle bundle = new Bundle();
                                intent.putExtra(Constants.PAYSTATEENTITY,
                                        payStateEntity);//1
                                if(memberinfo != null) {
                                    intent.putExtra("beformemberincahrgeinfo",
                                            memberinfo);//1
                                }
                                intent.putExtra("orderid", orderid);
                                intent.putExtra(Constants.GOTO_PAYSTATE_TYPE,
                                        Constants.SCANCODECOLLECTION_TO_STATE);
                                intent.putExtra("money", realMoney);
                                intent.putExtra("sucess", "8");

                                intent.putExtra("beizhu", beizhu);
//                                intent.putExtra("orderid", orderid);
                                startActivity(intent);
                                finish();
                            }
                            if(pDialog != null) {
                                pDialog.dismiss();
                                pDialog = null;
                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(ScanningActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(payStateEntity.getErrMsg());
                            //扫码错误，弹出提示且关闭
                            errorClos();
                        } else {

                            endDate = new Date(System.currentTimeMillis());
                            long diff = endDate.getTime() - startDate.getTime();
                            if(diff > looptime) {
                                if(looptime == 0) {
                                    return;
                                }

                                pDialog.setTitleText("收款失败")
                                        .setConfirmText("重新收款")
                                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                if(cp != null) {
                                                    cp.start();
                                                }
                                                pDialog.dismissWithAnimation();
                                            }
                                        })
                                        .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                                return;
                            }


                            try {
                                TimerTask task = new TimerTask() {
                                    @Override
                                    public void run() {
                                        /**
                                         *要执行的操作
                                         */
                                        Looper.prepare();
                                        payState(orderid, resulttype, money, beizhu);
                                        Looper.loop();
                                    }
                                };
                                Timer timer = new Timer();
                                timer.schedule(task, 2000);//2秒后执行TimeTask的run方法
                            } catch(Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(pDialog != null) {
                            pDialog.dismiss();
                            pDialog = null;
                        }
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });

    }

    //1.绑定Guid   apiblbl.aduer.com   "139QXEKV9Hj"
    private void postNetForBandGuid(String guid1) {
        String deviceID = Hawk.get("DeviceID");
        String url = Constants.BASE_URL + "/api/PosDeviceRegedit";
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = null;
        if(deviceID != null) {
            body = new FormBody.Builder()
                    .add("pos", CommonData.shebeiId())
                    .add("guid", guid1)
                    .add("deviceid", deviceID)
                    .build();
        } else {
            body = new FormBody.Builder()
                    .add("pos", CommonData.shebeiId())
                    .add("guid", guid1)
                    .build();
        }

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String stringjson = response.body().string();
            // "1|10014186|6359444303226545|测试45|许家琪|||"
            getFromString(stringjson);
        } catch(Exception e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(e instanceof SocketTimeoutException) {
                        Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                    } else if(e instanceof ConnectException) {
                        Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

    }

    //2.解析请求数据
    public void getFromString(String json) {
        BindGuidModel m;
        String s1 = json.substring(1, json.length() - 1);// 去掉返回字符串两边的 "
        String[] str = s1.split("\\|");
        if("1".equals(str[0])) {
//            business_login_submit.setClickable(false);
            String[] ar = new String[7];
            m = new BindGuidModel(str[0], str[1], str[2], str[3], str[4],
                    str.length > 5 ? str[5] : "", str.length > 6 ? str[6] : "");
            m.toString();
            //存入数据库(Hawk数据库中)
            LogUtils.e("绑定结果", m.toString());
            Hawk.put("DeviceID", m.getDeviceId());
            Hawk.put("DeviceSecret", m.getDeviceSecret());

            //存入数据库中
            SecrectAction secrectInstance = new SecrectAction(ScanningActivity.this);
            String queryData = secrectInstance.queryData();
            if(queryData != null) {
                // 解绑之后再次绑定，清空数据库
                secrectInstance.deleteData();
            }
            ContentValues values = new ContentValues();
            values.put("DeviceID", m.getDeviceId());
            values.put("DeviceSecret", m.getDeviceSecret());
            Long saveData = secrectInstance.saveData(values);
            if(saveData > 0)
                secrectInstance.closeDB();
            // 关闭数据库

//            Logger.d("m"+m);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(pDialog != null) {
                        pDialog.dismiss();//进度条消失
                    }
                    bandOrUnbandGuidResultDialog =
                            new BandOrUnbandGuidResultDialog(ScanningActivity.this,
                                    R.style.loading_dialog, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    bandOrUnbandGuidResultDialog.dismiss();
                                }
                            }, 100);
                    bandOrUnbandGuidResultDialog.show();
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            Intent intent = new Intent(ScanningActivity.this,
                                    LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }, 3200);

                }
            });
            //隐藏dailog
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(pDialog != null) {
                        pDialog.dismiss();//进度条消失
                    }
                    //失败结果的弹窗
                    bandGuidfaid =
                            new BandOrUnbandGuidResultDialog(ScanningActivity.this,
                                    R.style.loading_dialog, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    bandGuidfaid.dismiss();
                                }
                            }, 101);
                    bandGuidfaid.show();
                }
            });
            return;
        }
    }

    private void preAuthoMoney(String erWeiMaResult) {
        if(TextUtils.isEmpty(realMoney)) return;
//        if (!isNumeric(erWeiMaResult)) return;
        HashMap<String, String> addParams = new HashMap<>();

        BigDecimal goodsMoney =
                new BigDecimal(getIntent().getStringExtra(Constants.PRE_AUTHO_PAY_MONEY))
                        .subtract(new BigDecimal(getIntent().getStringExtra(Constants.PRE_AUTHO_PAY_DEPOSIT)));

        addParams.put("GoodsMoney", goodsMoney.toString());
        addParams.put("DepositMoney",
                getIntent().getStringExtra(Constants.PRE_AUTHO_PAY_DEPOSIT));
        addParams.put("Remark",
                getIntent().getStringExtra(Constants.PRE_AUTHO_PAY_REMARK));
        addParams.put("AuthCode", erWeiMaResult);

        APIRetrofit.getAPIService().preAuthoPay(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity -> {
                    if(pDialog == null) {
                        pDialog = new SweetAlertDialog(ScanningActivity.this,
                                SweetAlertDialog.PROGRESS_TYPE);
                        pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                "#005fee"));
                        pDialog.setTitleText("正在付款中");
                        pDialog.setCancelable(true);
                        pDialog.show();
                    } else {
                        pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                "#005fee"));
                        pDialog.setTitleText("正在付款中");
                        pDialog.setCancelable(true);
                        pDialog.show();
                    }
                    if(entity.getSuccess() == 1) {
                        startDate = new Date(System.currentTimeMillis());
                        preAuthoPayState(entity.getData().getOrderID());
                    } else {
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                        ToastUtils.showToast(ScanningActivity.this,
                                entity.getErrMsg());
                        finish();
                    }
                }, throwable -> {
                    if(pDialog != null && pDialog.isShowing())
                        pDialog.dismiss();
                });
    }

    /**
     * 获取预授权支付状态
     *
     * @param orderid
     */
    private void preAuthoPayState(String orderid) {
        if(TextUtils.isEmpty(orderid)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OrderID", orderid);
        APIRetrofit.getAPIService().preAuthoPayState(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(payStateEntity -> {
                    if(payStateEntity.getSuccess() == 1 && payStateEntity.getData().getOrderState() == 1) {
                        Intent intent = new Intent(ScanningActivity.this,
                                PreAuthoOrderActivity.class);
                        intent.putExtra("orderid", orderid);
                        intent.putExtra("tag", "result");
                        startActivity(intent);
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                        finish();
                    } else {
                        endDate = new Date(System.currentTimeMillis());
                        long diff = endDate.getTime() - startDate.getTime();
                        if(diff > looptime) {
                            if(pDialog != null && pDialog.isShowing())
                                pDialog.dismiss();
                            if(looptime == 0) {
                                return;
                            }
                            ToastUtils.showToast(ScanningActivity.this,
                                    getResources().getString(R.string.text_pay_overtime));
                            Intent intent = new Intent(ScanningActivity.this,
                                    PreAuthoOrderActivity.class);
                            intent.putExtra("orderid", orderid);
                            intent.putExtra("tag", "result");
                            startActivity(intent);
                            finish();
                            return;
                        }
                        try {
                            TimerTask task = new TimerTask() {
                                @Override
                                public void run() {
                                    /**
                                     *要执行的操作
                                     */
                                    Looper.prepare();
                                    preAuthoPayState(orderid);
                                    Looper.loop();
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task, 2000);//2秒后执行TimeTask的run方法
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, throwable -> {
                    if(pDialog != null && pDialog.isShowing())
                        pDialog.dismiss();
                });
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if(!isNum.matches()) {
            return false;
        }
        return true;
    }


    private void postnetformemberinfo(String memberNo, PayStateEntity payStateEntity,
                                      MemberInfoEntity.DataBean memberinfo,
                                      String orderid, String realMoney, String sucess,
                                      String sendmoney, String beizhu) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("scanMemberNo", memberNo);
        APIRetrofit.getAPIService().getMemberinfo(RXRequest.getXingPosParams(addParams,
                this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<MemberInfoEntity>() {
                    @Override
                    public void onNext(MemberInfoEntity memberInfoEntity) {
                        int success = memberInfoEntity.getSuccess();
                        if(success == 1) {
                            Intent intent = new Intent(ScanningActivity.this,
                                    ResultActivity.class);
                            intent.putExtra(Constants.PAYSTATEENTITY, payStateEntity);//1
                            if(memberInfoEntity.getData() != null) {
                                intent.putExtra("beformemberincahrgeinfo",
                                        memberInfoEntity.getData());//1
                            }
//                            intent.putExtra("orderid", orderid);
                            intent.putExtra("orderid", fromOrderID);
                            intent.putExtra(Constants.GOTO_PAYSTATE_TYPE,
                                    Constants.SCANCODECOLLECTION_TO_STATE);
                            intent.putExtra("money", realMoney);
                            intent.putExtra("sucess", sucess);
                            intent.putExtra("beizhu", beizhu);
                            //=============================
                            intent.putExtra("scanMemberNo", memberNo);
                            intent.putExtra("memberinfo", memberInfoEntity);
                            intent.putExtra("sendmoney", sendmoney);
                            startActivity(intent);
                            finish();
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            startActivity(new Intent(ScanningActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(memberInfoEntity.getErrMsg());
                            //// TODO: 2017/12/9 0009 去登录的界面
                            //扫码错误，弹出提示且关闭
                            errorClos();
                        } else {
                            Intent intent = new Intent(ScanningActivity.this,
                                    ResultActivity.class);
                            intent.putExtra(Constants.PAYSTATEENTITY, payStateEntity);//1
                            if(memberInfoEntity.getData() != null) {
                                intent.putExtra("beformemberincahrgeinfo",
                                        memberInfoEntity.getData());//1
                            }
                            intent.putExtra("orderid", orderid);
                            intent.putExtra(Constants.GOTO_PAYSTATE_TYPE,
                                    Constants.SCANCODECOLLECTION_TO_STATE);
                            intent.putExtra("money", realMoney);
                            intent.putExtra("sucess", sucess);
                            intent.putExtra("beizhu", beizhu);
                            intent.putExtra("scanMemberNo", memberNo);
                            intent.putExtra("memberinfo", memberInfoEntity);
                            intent.putExtra("sendmoney", sendmoney);
                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(ScanningActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(ScanningActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof UnknownHostException) {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ScanningActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    private void memberScanConsume(String mScanResults) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("MemberId", getIntent().getStringExtra(Constants.MEMBERID));
        addParams.put("OrderMoney", getIntent().getStringExtra(Constants.ORDER_MONEY));
        addParams.put("ScanCode", mScanResults);
        addParams.put("Remark", beizhu);
        APIRetrofit.getAPIService().memberConsume(RXRequest.getXingPosParams(addParams
                , this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(entity -> {
                    if(pDialog == null) {
                        pDialog = new SweetAlertDialog(ScanningActivity.this,
                                SweetAlertDialog.PROGRESS_TYPE);
                        pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                "#005fee"));
                        pDialog.setTitleText("正在付款中");
                        pDialog.setCancelable(true);
                        pDialog.show();
                    } else {
                        pDialog.getProgressHelper().setBarColor(Color.parseColor(
                                "#005fee"));
                        pDialog.setTitleText("正在付款中");
                        pDialog.setCancelable(true);
                        pDialog.show();
                    }
                    if(entity.getSuccess() == 1) {
                        startDate = new Date(System.currentTimeMillis());
                        String posOrderId = entity.getData().getPosOrderId();//收付款流水号
                        String memberOrderId = entity.getData().getOrderId();//会员订单号
                        memberScanConsumeState(posOrderId,memberOrderId);
                    } else {
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                        ToastUtils.showToast(ScanningActivity.this,
                                entity.getErrMsg());
                        finish();
                    }
                }, throwable -> {
                    if(pDialog != null && pDialog.isShowing())
                        pDialog.dismiss();
                });
    }


    private void memberScanConsumeState(String posOrderId,String memberOrderId) {
        if(TextUtils.isEmpty(posOrderId)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("orderid", posOrderId);
        APIRetrofit.getAPIService()
                .payState(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(payStateEntity -> {
                    if(payStateEntity.getSuccess() == 1) {
                        Intent intent = new Intent(ScanningActivity.this,
                                ResultActivity.class);
                        intent.putExtra(Constants.PAYSTATEENTITY,
                                payStateEntity);//1
                        intent.putExtra("orderid", posOrderId);
                        intent.putExtra(Constants.GOTO_PAYSTATE_TYPE,
                                Constants.SCANCODECOLLECTION_TO_STATE);
                        intent.putExtra("money", realMoney);
                        intent.putExtra("sucess", "8");
                        intent.putExtra("memberOrderId",memberOrderId);
                        intent.putExtra("beizhu", beizhu);
                        intent.putExtra("isMember",isMember);
                        startActivity(intent);
                        if(pDialog != null && pDialog.isShowing())
                            pDialog.dismiss();
                        finish();
                    } else {
                        endDate = new Date(System.currentTimeMillis());
                        long diff = endDate.getTime() - startDate.getTime();
                        if(diff > looptime) {
                            if(pDialog != null && pDialog.isShowing())
                                pDialog.dismiss();
                            if(looptime == 0) {
                                return;
                            }
                            pDialog.setTitleText("收款失败")
                                    .setConfirmText("重新收款")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            if(cp != null) {
                                                cp.start();
                                            }
                                            pDialog.dismissWithAnimation();
                                        }
                                    })
                                    .changeAlertType(SweetAlertDialog.ERROR_TYPE);
                            return;
                        }
                        try {
                            TimerTask task = new TimerTask() {
                                @Override
                                public void run() {
                                    /**
                                     *要执行的操作
                                     */
                                    Looper.prepare();
                                    memberScanConsumeState(posOrderId,memberOrderId);
                                    Looper.loop();
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task, 2000);//2秒后执行TimeTask的run方法
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, throwable -> {
                    if(pDialog != null && pDialog.isShowing())
                        pDialog.dismiss();
                });
    }


}
